package com.geekaca.web.servlet;

import com.geekaca.web.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(urlPatterns = "/register")
public class RegServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        UserService userService = new UserService();
        resp.setCharacterEncoding("utf-8");
        //验证码逻辑
        HttpSession session = req.getSession();
        String code = (String) session.getAttribute("checkCode");

        String username = req.getParameter("username");
        String password = req.getParameter("password");

        // 判断用户名是否已使用
        int i = userService.ifExistUser(username);
        if (i > 0) {
            session.setAttribute("register_msg", "用户名已使用...");
            resp.sendRedirect("/JSP814/register.jsp");
            return;
        }


        String checkCode = req.getParameter("checkCode");
        if (code != null && code.equals(checkCode)) {
            //验证码正确
            PrintWriter writer = resp.getWriter();
            session.removeAttribute("register_msg");
            int cnt = userService.addUser(username, password);
            if (cnt == 1) {
                System.out.println("注册成功");
                resp.sendRedirect("/JSP814/login.jsp");
            } else {
                System.out.println("注册失败");
                writer.write("注册失败！");
            }

        } else {
            // 验证码不正确
            PrintWriter writer = resp.getWriter();
            session.setAttribute("register_msg", "验证码不正确");
            resp.sendRedirect("/JSP814/register.jsp");
        }

    }
}
